package netty.protocolTCP;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * description:
 * author:zt
 * date:2021-10-09
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();

        System.out.println("服务器接收到的数据如下：");
        System.out.println("长度 = " + len);
        System.out.println("内容 = " + new String(content, Charset.forName("utf-8")));
        System.out.println("服务器接收到的数据包的数量 = " + (++this.count));

        //回复消息
        String reMsg = UUID.randomUUID().toString();
        byte[] response = reMsg.getBytes("utf-8");
        int reLen = response.length;
        //返回的数据格式
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLen(reLen);
        messageProtocol.setContent(response);

        ctx.writeAndFlush(messageProtocol);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
